import 'package:adaptive_dialog/adaptive_dialog.dart';

import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
import 'package:sainbainu/common/values/colors.dart';
import 'package:sainbainu/common/widgets/widget.dart';

import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import 'index.dart';
import 'widgets/widgets.dart';

class ContentCreatePage extends GetView<ContentCreateController> {
  const ContentCreatePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ContentCreateController>(
      init: ContentCreateController(),
      builder: (_) {
        return KeyboardClose(
          child: Scaffold(
            appBar: _buildAppBar(),
            body: _buildBody(),
            // bottomNavigationBar: _buildBottomBtns(),
          ),
        );
      },
    );
  }

  // 主视图
  Widget _buildBody() {
    return Column(
      children: [
        Expanded(
          child: GetBuilder<ContentCreateController>(
            id: 'reorder',
            builder: (_) {
              return ReorderableListView(
                padding: const EdgeInsets.fromLTRB(15, 15, 15, 0),
                onReorder: _.handleReorder,
                children: _.state.orderableFormTypes.map(
                  (FormType formType) {
                    return getFormChild(formType);
                  },
                ).toList(),
              );
            },
          ),
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 15),
          child: OutlinedFormBox(
            onTap: () => showSelectGroupPopup(),
            child: _buildGroupInput(),
          ),
        ),
        _buildBottomBtns()
      ],
    );
  }

  /// 获取表单组件
  Widget getFormChild(FormType formType) {
    switch (formType) {
      case FormType.image:
        return OutlinedFormBox(
          key: ValueKey(formType),
          rightIcon: const Icon(
            Icons.drag_indicator_rounded,
            color: AppColors.unactive4,
          ),
          child: ImageUploader(
            controller: controller.state.imageUploaderController,
            selectedCallback: (images) {
              controller.handleImageChange(images);
            },
          ),
        );
      case FormType.video:
        return OutlinedFormBox(
          key: ValueKey(formType),
          rightIcon: const Icon(
            Icons.drag_indicator_rounded,
            color: AppColors.unactive4,
          ),
          child: _buildVideo(),
        );
      case FormType.audio:
        return OutlinedFormBox(
          key: ValueKey(formType),
          rightIcon: const Icon(
            Icons.drag_indicator_rounded,
            color: AppColors.unactive4,
          ),
          child: Recorder(
            controller: controller.state.customRecorderController,
            recordedCallback: (path, duration) {
              controller.handleAudioChange(path, duration);
            },
            recordRemoveCallback: () {
              controller.handleAudioChange(null, null);
            },
          ),
        );
      case FormType.link:
        return Obx(
          key: ValueKey(formType),
          () => OutlinedFormBox(
            iconChild: controller.state.linkIsEmpty.value
                ? Image.asset(
                    'assets/images/input-link.png',
                    width: 24,
                    height: 24,
                  )
                : null,
            rightIcon: const Icon(
              Icons.drag_indicator_rounded,
              color: AppColors.unactive4,
            ),
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
            child: _buildLinkField(),
          ),
        );
      case FormType.text:
        return OutlinedFormBox(
          key: ValueKey(formType),
          rightIcon: const Icon(
            Icons.drag_indicator_rounded,
            color: AppColors.unactive4,
          ),
          child: _buildTextField(),
        );
      default:
        return const SizedBox.shrink();
    }
  }

  /// 构建选择视频
  Widget _buildVideo() {
    return AspectRatio(
      aspectRatio: 16 / 9,
      child: GetBuilder<ContentCreateController>(
        id: 'asset_video',
        builder: (_) {
          if (_.state.video != null) {
            return InkWell(
              onTap: () => showVideoBottomSheet(),
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(6),
                ),
                child: AssetEntityImage(
                  _.state.video!,
                  isOriginal: false,
                  fit: BoxFit.contain,
                ),
              ),
            );
          }
          return GestureDetector(
            onTap: () => controller.handleChooseVideo(),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(6),
              ),
              alignment: Alignment.centerLeft,
              child: Image.asset(
                'assets/images/input-video.png',
                width: 24,
                height: 24,
              ),
            ),
          );
        },
      ),
    );
  }

  /// ios 风格底部选择器
  Future<void> showVideoBottomSheet() async {
    String? res = await showModalActionSheet<String>(
      context: Get.context!,
      style: AdaptiveStyle.iOS,
      actions: [
        SheetAction(
          key: 'select',
          label: '重新选择'.tr,
        ),
        SheetAction(
          key: 'remove',
          label: '删除'.tr,
          isDestructiveAction: true,
        ),
      ],
    );
    if (res == 'select') {
      controller.handleChooseVideo();
    } else if (res == 'remove') {
      controller.handleRemoveVideo();
    }
  }

  /// 构建文本表单
  Widget _buildTextField() {
    return TextField(
      controller: controller.state.contentEditingController,
      focusNode: controller.state.contentFocusNode,
      maxLength: 255,
      maxLines: 3,
      decoration: InputDecoration(
        hintText: '请输入文字内容'.tr,
        border: InputBorder.none,
        contentPadding: const EdgeInsets.all(0),
      ),
    );
  }

  /// 构建链接表单
  Widget _buildLinkField() {
    return TextField(
      controller: controller.state.linkEditingController,
      focusNode: controller.state.linkFocusNode,
      decoration: const InputDecoration(
        // hintText: '输入或粘贴链接'.tr,
        border: InputBorder.none,
        contentPadding: EdgeInsets.all(0),
      ),
    );
  }

  /// 构建小组表单
  Widget _buildGroupInput() {
    return Container(
      height: 30,
      alignment: Alignment.centerLeft,
      child: Obx(() {
        if (controller.state.groupName.value.isEmpty) {
          return Image.asset(
            'assets/images/input-group.png',
            width: 24,
            height: 24,
          );
        } else {
          return Row(
            children: [
              Container(
                width: 30,
                height: 30,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4),
                ),
                clipBehavior: Clip.antiAlias,
                child: CustomImage(
                  url: controller.state.groupCover,
                ),
              ),
              const SizedBox(width: 10),
              Expanded(
                child: Text(
                  controller.state.groupName.value,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(
                    color: AppColors.active,
                    fontSize: 15,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
              InkWell(
                onTap: controller.clearGroupSelect,
                enableFeedback: true,
                child: Container(
                  width: 30,
                  height: 30,
                  alignment: Alignment.center,
                  child: const Icon(
                    Icons.cancel_rounded,
                    color: AppColors.unactive4,
                    size: 20,
                  ),
                ),
              )
            ],
          );
        }
      }),
    );
  }

  /// 构建小组选择器
  showSelectGroupPopup() async {
    showBarModalBottomSheet(
      context: Get.context!,
      // 如果子组件是滚动组件 则下拉关闭会很费劲 所以调整一下关闭阈值
      closeProgressThreshold: 0.85,
      builder: (context) => GroupSelectWidget(
        selectedGroupId: controller.state.groupId,
        onSelectTap: (item) => controller.handleGroupSelected(item),
      ),
    );
  }

  /// build appbar
  AppBar _buildAppBar() {
    return AppBar(
      title: Text('发布帖子'.tr),
      leading: IconButton(
        onPressed: () => controller.onClosePage(),
        icon: const Icon(Icons.close),
      ),
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
    );
  }

  /// bottom clear an create button
  Widget _buildBottomBtns() {
    return SafeArea(
      top: false,
      bottom: true,
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 15),
        child: Row(
          children: [
            Expanded(
              flex: 1,
              child: ElevatedButton(
                onPressed: () => controller.resetAll(),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColors.primary,
                  foregroundColor: Colors.white,
                  enableFeedback: true,
                ),
                child: Text('全部清空'.tr),
              ),
            ),
            const SizedBox(width: 15),
            Expanded(
              flex: 2,
              child: GetBuilder<ContentCreateController>(
                id: 'submitBtn',
                builder: (_) {
                  void Function()? onPressed;
                  if (_.state.text.isEmpty &&
                      _.state.linkIsEmpty.value &&
                      _.state.images.isEmpty &&
                      _.state.video == null &&
                      _.state.audio == null &&
                      _.state.groupId == null) {
                    onPressed = null;
                  } else {
                    onPressed = _.onPublish;
                  }
                  return ElevatedButton(
                    onPressed: onPressed,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColors.danger,
                      foregroundColor: Colors.white,
                      enableFeedback: true,
                    ),
                    child: Text('发布'.tr),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
